package com.liu.keeppwd;

import java.util.List;

import com.liu.common.MyBlueTooth;
import com.liu.common.MySocket;
import com.liu.db.DbConn;
import com.liu.db.MyDatabaseHelper;
import com.liu.model.Conn;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class CheckConnService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	public void onCreate() {
		super.onCreate();
	}

	class ch implements Runnable {
		Conn co;

		@Override
		public void run() {
			co.setState(0);
			co.setChecking(true);
			if (co.getLx().equals("1")) {
				if (MyBlueTooth.checkConn(co.getDz(),co.getTxmy())) {
					co.setState(1);
				}
			} else {
				String[] ips = co.getDz().split(":");
				if (MySocket.checkConn(ips[0], Integer.parseInt(ips[1]),co.getTxmy())) {
					co.setState(1);
				}
			}
			co.setChecking(false);
		}

	}

	static boolean key = false;
	Handler han;

	public void onStart(Intent intent, int startId) {
		if (key)
			return;
		key = true;
		han = new Handler();
		Log.i("123", "start");
		try {
			MyDatabaseHelper db = new MyDatabaseHelper(this);
			final List<Conn> lst = DbConn.Select(db.getReadableDatabase());
			
			for (int i = 0; i < lst.size(); i++) {
				ch t = new ch();
				t.co = lst.get(i);
				new Thread(t).start();
			}
			new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					han.post(new Runnable() {

						@Override
						public void run() {
							MyDatabaseHelper db = new MyDatabaseHelper(
									CheckConnService.this);
							for (int i = 0; i < lst.size(); i++) {
								Conn co = lst.get(i);
								Log.i("123",
										co.getTitle() + ":" + co.getState());
								try {
									db.Write(DbConn.AddRawData(co));
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						}
					});

				}

			}).start();

		} catch (Exception e) {
			e.printStackTrace();
		}
		key = false;
	}

}
